// 移动端排行榜逻辑

// Toast提示
function showToast(message, duration = 2000) {
    const toast = document.createElement('div');
    toast.className = 'toast';
    toast.textContent = message;
    document.body.appendChild(toast);

    setTimeout(() => {
        toast.style.animation = 'fadeOut 0.3s';
        setTimeout(() => toast.remove(), 300);
    }, duration);
}

let currentType = 'total';

// 切换筛选类型
document.querySelectorAll('.filter-tab').forEach(tab => {
    tab.addEventListener('click', () => {
        document.querySelectorAll('.filter-tab').forEach(t => t.classList.remove('active'));
        tab.classList.add('active');
        currentType = tab.dataset.type;
        loadLeaderboard();
    });
});

// 加载排行榜
async function loadLeaderboard() {
    const topThree = document.getElementById('topThree');
    const leaderboardList = document.getElementById('leaderboardList');

    // 显示加载状态
    topThree.innerHTML = `
        <div class="loading">
            <div class="spinner"></div>
            <span>加载中...</span>
        </div>
    `;
    leaderboardList.innerHTML = '';

    try {
        const response = await fetch(`/api/leaderboard?type=${currentType}`);
        const data = await response.json();

        if (data.success && data.leaderboard && data.leaderboard.length > 0) {
            displayLeaderboard(data.leaderboard, data.my_rank);
        } else {
            topThree.innerHTML = `
                <div class="empty-state">
                    <div class="empty-icon">📊</div>
                    <div class="empty-text">暂无排行数据</div>
                </div>
            `;
        }
    } catch (error) {
        console.error('加载排行榜错误:', error);
        topThree.innerHTML = `
            <div class="empty-state">
                <div class="empty-icon">❌</div>
                <div class="empty-text">加载失败</div>
            </div>
        `;
    }
}

// 显示排行榜
function displayLeaderboard(leaderboard, myRank) {
    const topThree = document.getElementById('topThree');
    const leaderboardList = document.getElementById('leaderboardList');

    // 清空
    topThree.innerHTML = '';
    leaderboardList.innerHTML = '';

    // 显示我的排名（如果有且不在前10）
    if (myRank && myRank.rank > 10) {
        const myRankCard = createMyRankCard(myRank);
        topThree.appendChild(myRankCard);
    }

    // 显示所有用户为列表形式
    leaderboard.forEach((user, idx) => {
        const item = createLeaderItem(user, idx + 1);
        leaderboardList.appendChild(item);
    });
}

// 创建排行榜项
function createLeaderItem(user, rank) {
    const div = document.createElement('div');
    div.className = 'leader-item';

    // 为前三名添加特殊样式
    if (rank === 1) div.classList.add('top-1');
    if (rank === 2) div.classList.add('top-2');
    if (rank === 3) div.classList.add('top-3');

    const value = getValueByType(user);
    const stats = getStatsText(user);

    // 前三名显示奖牌，其他显示数字
    let rankDisplay = '';
    let rankClass = 'rank-normal';

    if (rank === 1) {
        rankDisplay = '🥇';
        rankClass = 'rank-1';
    } else if (rank === 2) {
        rankDisplay = '🥈';
        rankClass = 'rank-2';
    } else if (rank === 3) {
        rankDisplay = '🥉';
        rankClass = 'rank-3';
    } else {
        rankDisplay = rank;
    }

    // 头像显示：优先使用头像图片，否则显示首字母
    const avatarHtml = user.avatar
        ? `<img src="${user.avatar}" class="leader-avatar-img" onerror="this.style.display='none'; this.parentElement.innerHTML='${user.username[0].toUpperCase()}';">`
        : user.username[0].toUpperCase();

    div.innerHTML = `
        <div class="leader-rank ${rankClass}">${rankDisplay}</div>
        <div class="leader-avatar">${avatarHtml}</div>
        <div class="leader-info">
            <div class="leader-name">${user.username}</div>
            <div class="leader-stats">${stats}</div>
        </div>
        <div class="leader-score">${value}</div>
    `;

    return div;
}

// 创建我的排名卡片
function createMyRankCard(myRank) {
    const div = document.createElement('div');
    div.className = 'my-rank-card';

    const value = getValueByType(myRank);

    div.innerHTML = `
        <div class="my-rank-title">👤 我的排名</div>
        <div class="my-rank-content">
            <div class="my-rank-number">#${myRank.rank}</div>
            <div class="my-rank-info">
                <div class="my-rank-stat">
                    <span>${getLabel()}</span>
                    <strong>${value}</strong>
                </div>
                <div class="my-rank-stat">
                    <span>答题次数</span>
                    <strong>${myRank.total_quizzes || 0}次</strong>
                </div>
                <div class="my-rank-stat">
                    <span>正确率</span>
                    <strong>${myRank.accuracy || 0}%</strong>
                </div>
            </div>
        </div>
    `;

    return div;
}

// 根据类型获取值
function getValueByType(user) {
    switch (currentType) {
        case 'total':
            return user.total_score || 0;
        case 'accuracy':
            return (user.accuracy || 0) + '%';
        case 'count':
            return user.total_quizzes || 0;
        default:
            return 0;
    }
}

// 获取标签
function getLabel() {
    switch (currentType) {
        case 'total':
            return '总分';
        case 'accuracy':
            return '正确率';
        case 'count':
            return '答题次数';
        default:
            return '';
    }
}

// 获取统计文本
function getStatsText(user) {
    switch (currentType) {
        case 'total':
            return `答题${user.total_quizzes || 0}次 · 正确率${user.accuracy || 0}%`;
        case 'accuracy':
            return `总分${user.total_score || 0} · 答题${user.total_quizzes || 0}次`;
        case 'count':
            return `总分${user.total_score || 0} · 正确率${user.accuracy || 0}%`;
        default:
            return '';
    }
}

// 设置当前导航项为激活状态
function setActiveNav() {
    const path = window.location.pathname;
    document.querySelectorAll('.nav-item').forEach(item => {
        item.classList.remove('active');
        if (item.getAttribute('href') === path) {
            item.classList.add('active');
        }
    });
}

// 页面加载时执行
document.addEventListener('DOMContentLoaded', () => {
    loadLeaderboard();
    setActiveNav();
});

// 添加fadeOut动画
const style = document.createElement('style');
style.textContent = `
    @keyframes fadeOut {
        from { opacity: 1; }
        to { opacity: 0; }
    }
`;
document.head.appendChild(style);
